import React, { useState, useEffect } from 'react';
import { Input, Row, Alert, Spin } from 'antd';
import axios from 'axios';
import moment from 'moment';
import { WeatherCard } from './components/WeatherCard';
import './styles.css';

interface WeatherData {
  fxDate: string;
  tempMax: string;
  tempMin: string;
  textDay: string;
  iconDay: string;
  humidity: string;
  windSpeedDay: string;
}

const API_KEY = 'a2a4ad7992574cc0861296f92e6c6a35'; // 和风天气API Key

const WeatherPage = () => {
  const [city, setCity] = useState('上海');
  const [weatherData, setWeatherData] = useState<WeatherData[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const fetchWeather = async (location: string) => {
    try {
      setLoading(true);
      setError('');
      
      // 先获取位置ID
      const locationRes = await axios.get(
        `https://geoapi.qweather.com/v2/city/lookup?key=${API_KEY}&location=${location}`
      );
      
      const locationId = locationRes.data.location[0].id;
      
      // 获取7天天气预报
      const weatherRes = await axios.get(
        `https://devapi.qweather.com/v7/weather/7d?key=${API_KEY}&location=${locationId}`
      );

      const formattedData = weatherRes.data.daily.map((item: any) => ({
        fxDate: moment(item.fxDate).format('MM/DD'),
        tempMax: item.tempMax,
        tempMin: item.tempMin,
        textDay: item.textDay,
        iconDay: item.iconDay,
        humidity: item.humidity,
        windSpeedDay: item.windSpeedDay
      }));

      setWeatherData(formattedData);
    } catch (err) {
      setError('获取天气数据失败，请检查城市名称');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchWeather(city);
  }, [city]);

  return (
    <div className="container">
      <h1>7日天气预报</h1>
      <Input.Search
        placeholder="请输入城市名称"
        defaultValue={city}
        onSearch={(value) => setCity(value.trim())}
        enterButton
        className="search-bar"
      />

      {error && <Alert message={error} type="error" showIcon />}

      <Spin spinning={loading}>
        <Row gutter={[16, 16]} className="weather-container">
          {weatherData.map((data, index) => (
            <WeatherCard key={index} data={data} />
          ))}
        </Row>
      </Spin>
    </div>
  );
};

export default WeatherPage;